/*
 * 路由组件的处理方法
 * @Author: ljb
 * @Date: 2018-11-09 16:48:29
 * @Last Modified by: ljb
 * @Last Modified time: 2019-06-04 09:05:22
 */
import iView from 'iview';
/* eslint-disable-next-line import/extensions */
import store from 'src/vuex/store';

import gTag from 'src/libs/analytics';

import { $t } from 'src/i18n';
import { parseQueryString } from 'src/utils/helper';

import Util from './libs/util';

/**
 * 格式化search参数
 * @return {String} {格式化后的参数字符串}
 */
function normalizeSearch() {
	const search = parseQueryString();
	return Object.keys(search)
		.map(key => `${key}/${search[key]}`)
		.join('/');
}

/**
 * 是否是需要校验的
 * @param  {String} name {路由名}
 * @return {boolean} {true代表是需要校验的路由}
 */
function needChecked(name) {
	const uncheckedRouters = [
		'login',
		'cust-login',
		'store-login',
		'reset',
		'authorize-status',
	];

	return uncheckedRouters.indexOf(name) === -1;
}

/**
 * 如果不是登录页面，则判断是否存在用户的token，不然就重新跳转会login页面
 * @param {Object} to {将要去到的路由对象to}
 * @return {boolean}
 */
function shouldLogOut(to) {
	return needChecked(to.name) && !store.state.userToken.user_token;
}

/**
 * 保存访问的路由地址
 * @param  {Object} to {路由的to}
 * @return {undefined}
 */
function checkUrl(from, to) {
	const param = {
		page: {
			title: to.meta.menu,
			name: to.path,
		},
		previous_page: {
			title: from.meta.menu,
			name: from.path,
		},
	};
	store.commit('menu/setCachepage', param);
}

/**
 * 是否是登录页面
 * @param  {String} name {需要判断的当前路由的name}
 * @return {Boolean} {true代表是登录页面}
 */
function isLoginPage(name) {
	return name === 'login' || name === 'cust-login' || name === 'store-login';
}

// iview相关的控制对象
const iviewControl = {
	// 进度条开始
	loadingStart() {
		iView.LoadingBar.start();
	},
	// 进度条结束
	loadingEnd() {
		iView.LoadingBar.finish();
	},
	// 显示错误信息
	showErrorMessage(msg, duration = 3) {
		iView.Message.error({
			content: msg, //
			duration,
		});
	},
};

/**
 * 重定向的处理操作
 * @param  {Object} to   {将要前往的路由对象}
 * @param  {Object} from {已经离开的路由对象}
 * @param  {Function} next {路由继续往下执行的方法}
 * @return {undefined}
 */
function redirectHandle(to, from, next) {
	if (isLoginPage(from.name)) {
		iView.LoadingBar.finish();
	} else {
		const to_path = to.fullPath;
		let login_path_new = '';

		if (to_path.indexOf('/admin') === 0) {
			login_path_new = '/login';
		} else if (to_path.indexOf('/customer') === 0) {
			login_path_new = '/cust-login';
		} else {
			login_path_new = '/store-login';
		}

		const login_path = sessionStorage.getItem('login_path') || login_path_new;

		next({
			path: login_path,
		});
	}
}

/**
 * 重定向流程
 * @param  {Object} to   {将要前往的路由对象}
 * @param  {Object} from {已经离开的路由对象}
 * @param  {Function} next {路由继续往下执行的方法}
 * @return {undefined}
 */
function redirectToLoginPage(to, from, next) {
	const err_msg = $t('common.no_auth');

	iviewControl.showErrorMessage(err_msg);

	setTimeout(redirectHandle(to, from, next), 3000);
}

// 路由处理方法
const handleRouter = {
	// 路由切换前的处理
	before(to, from, next) {
		// iview show loading
		iviewControl.loadingStart();

		gTag('event', 'page_view', {
			page_path: window.location.pathname + normalizeSearch() + window.location.hash,
		});

		// reset title
		Util.title(to.meta.title);

		if (shouldLogOut(to)) {
			return redirectToLoginPage(to, from, next);
		}

		if (needChecked(to.name)) {
			checkUrl(from, to);
		}
		return next();
	},
	// 路由切换后的处理
	after() {
		iviewControl.loadingEnd();
		window.scrollTo(0, 0);
	},
};

export default handleRouter;
